<script setup lang='ts'>
import type { VxeGridInstance, VxeGridProps, VxePagerEvents } from 'vxe-table'

import { addEarnestMoney, addOutTime, batchMoney, batchOutTime, projectIdPageList } from '@fl/api/anjutong'
import UpLoadFileOss from '@fl/components/upLoadFile-oss.vue'

const state = ref({
    projectName: '',
})
const formTypeEnum = {
    batchEarnestMoney: '批量修改诚意金',
    batchOutTime: '批量修改退款时间',
    edit: '诚意金设置',
    refundSetting: '退款设置',
} as const
const formType = ref()
const centerDialogVisible = ref(false)
const columns = [
    {
        colProps: {
            span: 6,
        },
        label: '项目名称',
        prop: 'projectName',
        valueType: 'copy',
    },
]
const submitLoading = ref(false)
const outTimeParams = ref({
    outStatus: false,
    outTime: null,
    projectId: '',
    projectName: '',
})
const outTimeColumns = [
    {
        label: '自动退款',
        prop: 'outStatus',
        valueType: 'switch',
    },
    {
        fieldProps: { min: 0, precision: 0 },
        label: '退款时间(单位天)',
        prop: 'outTime',
        valueType: 'input-number',
    },

]
const selectValue = ref<any[]>()
const earnestMoneyParams = ref({
    agreementUrl: '',
    earnestMoney: 0,
    // pactUrl: '',
    projectId: '',
    projectName: '',
})
const earnestMoneyColumns = [
    {
        fieldProps: { min: 0, precision: 0 },
        label: '诚意金',
        prop: 'earnestMoney',
        valueType: 'input-number',
    },
    {
        label: '认购协议',
        prop: 'agreementUrl',
    },
    /* {
        label: '上链公约',
        prop: 'pactUrl',
    }, */
]
const rules = {
    agreementUrl: [
        {
            message: '请上传认购协议',
            required: true,
        },
    ],
    earnestMoney: [
        {
            message: '请输入诚意金',
            required: true,
        },
    ],
    outStatus: [
        {
            message: '请选择状态',
            required: true,
        },
    ],
    outTime: [
        {
            message: '请输入退款时间',
            required: true,
        },
    ],
    /* pactUrl: [
        {
            message: '请上传上链公约',
            required: true,
        },
    ], */
}

const dialogTitle = computed(() => {
    if (formType.value)
        return formType.value

    return ''
})
type RowVO = {
    address: string
    company: string
    outTime: string
    sumary: string
    xmmc: string
}
const xGrid = ref<VxeGridInstance<RowVO>>()
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const gridOptions = reactive<VxeGridProps<RowVO>>({
    align: 'center',
    columnConfig: {
        resizable: true,
    },
    columns: [
        { type: 'checkbox', width: 50 },
        { field: 'xmmc', title: '项目名称' },
        { field: 'company', title: '企业名称' },
        { field: 'address', title: '地址' },
        { field: 'sumary', title: '简介' },
        { field: 'outTime', title: '退款时间(单位天)' },
        { field: 'outStatus', slots: { default: 'outStatus' }, title: '自动退款' },
        { field: 'agreementUrl', slots: { default: 'agreementUrl' }, title: '认购协议' },
        // { field: 'pactUrl', slots: { default: 'pactUrl' }, title: '上链公约' },
        { field: 'earnestMoney', title: '诚意金(分)' },
        { slots: { default: 'operate' }, title: '操作', width: 300 },

    ],
    data: [

    ],
    editConfig: {
        mode: 'row',
        showStatus: true,
        trigger: 'manual',
    },
    height: 530,
    keepSource: true,
    loading: false,
    showOverflow: true,
})
function search() {
    tablePage.currentPage = 1
    findList()
}
function reset() {
    state.value = {
        projectName: '',
    }
    findList()
}
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
    findList()
}

async function findList() {
    gridOptions.loading = true
    try {
        const options = {
            pageNum: tablePage.currentPage,
            pageSize: tablePage.pageSize,
            projectName: state.value.projectName,
        }
        const data = await projectIdPageList(options)
        console.log('🚀 ~ findList ~ data:', data)
        gridOptions.loading = false
        // console.log('🚀 ~ findList ~ data:', data)
        tablePage.total = data?.total
        gridOptions.data = data?.data
    }
    catch (error) {
        gridOptions.loading = false
    }
}
findList()
async function handleSubmit() {
    submitLoading.value = true
    try {
        if (formType.value === formTypeEnum.refundSetting) { // 退款设置
            const options = {
                outStatus: outTimeParams.value.outStatus ? 1 : 2,
                outTime: outTimeParams.value.outTime ?? 0,
                projectId: outTimeParams.value.projectId,
                projectName: outTimeParams.value.projectName,
            }
            await addOutTime(options)
            ElMessage.success('修改成功')
        }
        if (formType.value === formTypeEnum.batchEarnestMoney) {
            const options = selectValue.value?.map((item: any) => {
                return {
                    agreementUrl: earnestMoneyParams.value.agreementUrl,
                    earnestMoney: earnestMoneyParams.value.earnestMoney ?? 0,
                    // pactUrl: earnestMoneyParams.value.pactUrl,
                    projectId: item.id,
                    projectName: item.xmmc,
                }
            })
            await batchMoney(options)
            ElMessage.success('修改成功')
            console.log('🚀 ~ options ~ options:', options)
        }

        if (formType.value === formTypeEnum.batchOutTime) {
            const options = selectValue.value?.map((item: any) => {
                return {
                    outStatus: outTimeParams.value.outStatus ? 1 : 2,
                    outTime: outTimeParams.value.outTime ?? 0,
                    projectId: item.id,
                    projectName: item.xmmc,
                }
            })
            await batchOutTime(options)
            ElMessage.success('修改成功')
            console.log('🚀 ~ options ~ options:', options)
        }
        if (formType.value === formTypeEnum.edit) {
            const options = {
                agreementUrl: earnestMoneyParams.value.agreementUrl,
                earnestMoney: earnestMoneyParams.value.earnestMoney ?? 0,
                // pactUrl: earnestMoneyParams.value.pactUrl,
                projectId: earnestMoneyParams.value.projectId,
                projectName: earnestMoneyParams.value.projectName,
            }
            console.log('🚀 ~ handleSubmit ~ options:', options)
            await addEarnestMoney(options)
            ElMessage.success('修改成功')
        }
        submitLoading.value = false
        centerDialogVisible.value = false
        findList()
    }
    catch (error) {
        submitLoading.value = false
    }
}
function showForm(row: any, type: string) {
    console.log('🚀 ~ showForm ~ row:', row)

    formType.value = type
    if (formType.value === formTypeEnum.refundSetting) {
        outTimeParams.value = {
            outStatus: row.outStatus === 1,
            outTime: row.outTime ?? 0,
            projectId: row.id,
            projectName: row.xmmc,
        }
    }
    if (formType.value === formTypeEnum.edit) {
        earnestMoneyParams.value = {
            agreementUrl: row?.agreementUrl,
            earnestMoney: row?.earnestMoney ?? 0,
            // pactUrl: row?.pactUrl,
            projectId: row?.id,
            projectName: row?.xmmc,
        }
    }
    centerDialogVisible.value = true
}
const formModel = computed(() => {
    if (formType.value === formTypeEnum.refundSetting || formType.value === formTypeEnum.batchOutTime)
        return outTimeParams.value
    if (formType.value === formTypeEnum.batchEarnestMoney || formType.value === formTypeEnum.edit)
        return earnestMoneyParams.value

    return ''
})
const formColumns = computed(() => {
    if (formType.value === formTypeEnum.refundSetting || formType.value === formTypeEnum.batchOutTime)
        return outTimeColumns
    if (formType.value === formTypeEnum.batchEarnestMoney || formType.value === formTypeEnum.edit)
        return earnestMoneyColumns
    return []
})
async function updateMoney() {
    formType.value = formTypeEnum.batchEarnestMoney
    const $table = xGrid.value
    if ($table) {
        const selectRecords: any[] = $table.getCheckboxRecords()
        if (selectRecords.length) {
            selectValue.value = selectRecords
            centerDialogVisible.value = true
        }

        else { ElMessage.warning('请至少选择一项数据') }
    }
}
async function updateTime() {
    formType.value = formTypeEnum.batchOutTime
    const $table = xGrid.value
    if ($table) {
        const selectRecords: any[] = $table.getCheckboxRecords()
        if (selectRecords.length) {
            selectValue.value = selectRecords
            centerDialogVisible.value = true
        }

        else { ElMessage.warning('请至少选择一项数据') }
    }
}
function resetFormParams() {
    outTimeParams.value = {
        outStatus: false,
        outTime: null,
        projectId: '',
        projectName: '',
    }
    earnestMoneyParams.value = {
        agreementUrl: '',
        earnestMoney: 0,
        // pactUrl: '',
        projectId: '',
        projectName: '',
    }
}
function preview(row: any, type: string) {
    try {
        const result = JSON.parse(row[type])
        if (result?.fileUrl)
            window.open(result?.fileUrl, '_blank')

        else
            ElMessage.error('暂无数据')
    }
    catch (error) {
        ElMessage.error('暂无数据')
    }
}
function showName(row: any, type: string) {
    try {
        const result = JSON.parse(row[type])
        if (result?.fileName)
            return result?.fileName

        else
            return ''
    }
    catch (error) {
        return ''
    }
}
</script>

<template>
    <div class="mb-20 flex bg-white p-30">
        <div class="flex-1 pr-24">
            <PlusForm v-model="state"
                      :columns="columns"
                      :row-props="{ gutter: 20 }"
                      label-width=""
                      :has-footer="false"
            />
        </div>

        <div>
            <ElButton type="primary"
                      @click="search"
            >
                搜索
            </ElButton>

            <ElButton @click="reset">
                重置
            </ElButton>
        </div>
    </div>

    <div class="bg-white p-30">
        <div class="mb-30">
            <ElButton @click="updateMoney">
                {{ formTypeEnum.batchEarnestMoney }}
            </ElButton>

            <ElButton @click="updateTime">
                {{ formTypeEnum.batchOutTime }}
            </ElButton>
        </div>

        <vxe-grid ref="xGrid"
                  v-bind="gridOptions"
        >
            <template #operate="{ row }">
                <el-button @click="showForm(row, formTypeEnum.edit)">
                    {{ formTypeEnum.edit }}
                </el-button>

                <el-button @click="showForm(row, formTypeEnum.refundSetting)">
                    {{ formTypeEnum.refundSetting }}
                </el-button>
            </template>

            <template #outStatus="{ row }">
                <vxe-switch :model-value="row.outStatus === 1"
                            disabled
                />
            </template>

            <template #agreementUrl="{ row }">
                <span class="cursor-pointer"
                      style=" color: var(--el-color-primary);"
                      @click="preview(row, 'agreementUrl')"
                >
                    {{ showName(row, 'agreementUrl') }}
                </span>
            </template>

            <!-- <template #pactUrl="{ row }">
                <span class="cursor-pointer"
                      style=" color: var(--el-color-primary);"
                      @click="preview(row, 'pactUrl')"
                >
                    {{ showName(row, 'agreementUrl') }}
                </span>
            </template> -->

            <template #pager>
                <vxe-pager v-model:current-page="tablePage.currentPage"
                           v-model:page-size="tablePage.pageSize"
                           background
                           :total="tablePage.total"
                           :layouts="['Home', 'PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'End', 'Sizes', 'FullJump', 'Total']"
                           @page-change="handlePageChange"
                />
            </template>
        </vxe-grid>
    </div>

    <el-dialog v-model="centerDialogVisible"
               :title="dialogTitle"
               width="800"
               destroy-on-close
               align-center
               :close-on-click-modal="false"
               @close="resetFormParams"
    >
        <PlusForm v-model="formModel"
                  :columns="formColumns"
                  :has-reset="false"
                  label-width="150"
                  :rules="rules"
                  :submit-loading="submitLoading"
                  @submit="handleSubmit"
        >
            <template #plus-field-agreementUrl>
                <UpLoadFileOss v-model="earnestMoneyParams.agreementUrl"
                               accept=".pdf"
                               @success="submitLoading = false"
                               @beforeupload="submitLoading = true"
                />
            </template>

            <!-- <template #plus-field-pactUrl>
                <UpLoadFileOss v-model="earnestMoneyParams.pactUrl"
                               accept=".pdf"
                />
            </template> -->
        </PlusForm>
    </el-dialog>
</template>
